package utils

import (
	"errors"
	"fmt"
	"net/url"

	"github.com/smartwalle/alipay/v3"
)

var (
	appId = "9021000128664144"
	// PrivateKey 私钥
	privateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCLgV60hmhD8Xjbq6ytASWwd9ZZ0hXgEEmBvNmTjPEtsz2+LjVvZ/eDDiZvKW1b/ReAx/BGgUMVgVv0eh8Li7XlUYIoUHnIzZAQw7PRJKYg4VWhXQElHjB1UnWMr7J3yP4BHu/1lr3jOnGxVO4aLwSdRkvbgR+VHvzHBsVp1hSdlx984g7Ctm1lxFARobHsP9rKXrvkgA9066u4QX2IId5fCbwY611uDRmHL8i+NXdLqxmXzMNgZsX6gbGC78mk1rjqibJcJhkBf77F61+54axNjVjLFlAsreKzrcFcxGSUjlNMkekp6AHym5oeZE6pHlxaH/9kZuY0HSKM2bHQ7SgrAgMBAAECggEAUHgoU8Nv4zkneLbXHNgbkGYfu6HmQl/CttZjPqw+9hh9FfV7ly6GZA9GdjqUPUqJQxyRaWnoc0Ax9Zx3yeYl3wgcJvr8tKp2XmU0lQAp3697AGAwZ+O5GgOdkLBMJrJGagkZazUvhSHSMPMHgQz8AWhqG0ypFhBQyNEMEJePPrLyTyZHlwHKK+F32PAwkRfAg/VVhpxKtCY4QcsY8s6IQF6tqR668G2293HTOdyYYIt7MPArzNa9mGhc6jWXN2Ka87FwPrhuLpW28YKl4zu7RP8WiPNRJi+Lz8BMZxVTPMvdCk7Qw5krkxwZxRmciaHphp8Zgr6o++iqU1zZGm1FEQKBgQC9XdL+f9A+wMpCVhRNquI/71BeuPcNk7UuTTQvksg9uPLtZ7QJqNnXGeWRlcsuhWI+PcJPgf/+1a9gxVcysqGFasapMqKsz7uriS6UOiQzsHe8w+cgdfamjNcDMAg7cmPV14d9735lbA3eUfZKvqqRMTaRXsREN8aS0bPmeb1RGQKBgQC8mArhVifvxqEIDFdm+A6gVg5Y3Qyt0sTQL1Irk+6vPHloIefNx4n1RCiT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client *alipay.Client
)

func init() {
	client, _ = alipay.New(appId, privateKey, false)
	client.LoadAliPayPublicKey(aliPublicKey)
}

func AliPay(subject string, outTradeNo string, totalAmount string) string {
	var p = alipay.TradePagePay{}
	p.NotifyURL = "http://c8mdhq.natappfree.cc/order/v1/notify"
	p.ReturnURL = "http://127.0.0.1:8080/order/v1/return"
	p.Subject = subject
	p.OutTradeNo = outTradeNo
	p.TotalAmount = totalAmount
	p.ProductCode = "FAST_INSTANT_TRADE_PAY"

	var url, err = client.TradePagePay(p)
	if err != nil {
		fmt.Println(err)
		return ""
	}

	// 这个 payURL 即是用于打开支付宝支付页面的 URL，可将输出的内容复制，到浏览器中访问该 URL 即可打开支付页面。
	var payURL = url.String()
	fmt.Println(payURL)
	return payURL
}

func Returns(values url.Values) (string, int, error) {
	notification, err := client.DecodeNotification(values)
	if err != nil {
		return "", -1, err
	}
	switch notification.TradeStatus {
	case alipay.TradeStatusSuccess: //支付成功
		return notification.OutTradeNo, 1, nil
	case alipay.TradeStatusWaitBuyerPay: //待支付
		return notification.OutTradeNo, 0, nil
	case alipay.TradeStatusClosed: //交易关闭
		return notification.OutTradeNo, 2, nil
	case alipay.TradeStatusFinished: //交易结束
		return notification.OutTradeNo, 3, nil
	default:
		return "", -1, errors.New("请求错误！")
	}
}
